package hhs.poc.activities.scanner.views;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder _holder;
    private Camera _camera;
    private Context _context;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        this._context = context;
        _camera = camera;
        
        _holder = getHolder();
        _holder.addCallback(this);
        
        // deprecated setting, but required on Android versions prior to 3.0
        _holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            _camera.setPreviewDisplay(holder);
            _camera.startPreview();
        } catch (IOException e) {
        	Toast.makeText(_context, "[Error] " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    	WindowManager windowMan = (WindowManager)(_context.getSystemService(Context.WINDOW_SERVICE));
    	Display display = windowMan.getDefaultDisplay();
    	int w = display.getWidth();
    	int h = display.getHeight();
    	
    	setMeasuredDimension(w, h);
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    	
        if (_holder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // stop preview before making changes
        try {
            _camera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

        Camera.Parameters params = _camera.getParameters();
        // params change here
        _camera.setParameters(params);

        // start preview with new settings
        try {
            _camera.setPreviewDisplay(_holder);
            _camera.startPreview();

        } catch (Exception e){
        	Toast.makeText(_context, "[Error] " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }
}
